package com.jingbit.ai.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.JetPlayer;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Log;

import com.jingbit.ai.AIApp;
import com.jingbit.ai.bean.MusicInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;


public class MediaUtil {
    private static MediaPlayer mPlayer;
    private volatile static boolean playing;

    public static void init() {
        //创建MediaPlayer和设置监听
        mPlayer = new MediaPlayer();
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                playing = false;
            }
        });
    }


    public static void loadMusics(final Context context, final IMusicListener listener) {
        new AsyncTask<Void, Void, List<MusicInfo>>() {

            String[] projections = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.DATA};
            String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

            @Override
            protected List<MusicInfo> doInBackground(Void... params) {
                List<MusicInfo> musicInfos = new ArrayList<>();

                Cursor cursor = context.getContentResolver()
                        .query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                                projections,
                                selection,
                                null,
                                null);

                while (cursor != null && cursor.moveToNext()) {
                    MusicInfo audioInfo = new MusicInfo();
                    int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
                    String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                    String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                    String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));

                    audioInfo.setId(id);
                    audioInfo.setTitle(title);
                    audioInfo.setArtist(artist);
                    audioInfo.setPath(path);
                    audioInfo.setDuration(duration);
                    musicInfos.add(audioInfo);
                }
                if (cursor != null) {
                    cursor.close();
                }
                return musicInfos;
            }

            @Override
            protected void onPostExecute(List<MusicInfo> musicInfos) {
                if (listener != null) {
                    listener.onCompleted(musicInfos);
                }
            }
        }.execute();
    }


    /**
     * 从assets资源文件夹中播放
     *
     * @param name
     */
    public static void playSoundFromA(Context context, String name) {
        if (playing) {
            return;
        }

        // 设置当前播放歌曲的名字
        mPlayer.reset();
        try {
            AssetFileDescriptor afd = context.getAssets().openFd(name);
            mPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mPlayer.prepareAsync();
            mPlayer.start();
            playing = true;
        } catch (IOException e) {
            e.printStackTrace();
            playing = false;
        }
    }

    public static void stop() {
        if (mPlayer != null) {
            mPlayer.stop();
        }
    }

    public static void release() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }

    public static AudioTrack audioTrack;

    // 从本地文件读取AudioTrack并播放
    public static void playLocalAudio(String audioFile) {
        stopPlay();
        File file = new File(audioFile);
        if (file.exists()) {
            // 获取音频文件信息
            int sampleRateInHz, channelConfig, audioFormat;
            int minBufferSize;
            try {
                MediaExtractor extractor = new MediaExtractor();
                extractor.setDataSource(audioFile);
                MediaFormat format = extractor.getTrackFormat(0);
                sampleRateInHz = format.getInteger(MediaFormat.KEY_SAMPLE_RATE);
                channelConfig = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT) ==
                        1 ? AudioFormat.CHANNEL_OUT_MONO : AudioFormat.CHANNEL_OUT_STEREO;
                audioFormat = format.containsKey(MediaFormat.KEY_PCM_ENCODING) ?
                        format.getInteger(MediaFormat.KEY_PCM_ENCODING) : AudioFormat.ENCODING_PCM_16BIT;
                minBufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
                extractor.release();
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }

            // 初始化AudioTrack并播放音频文件
            byte[] buffer = new byte[minBufferSize];
            try {
                FileInputStream fis = new FileInputStream(audioFile);
                AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                        sampleRateInHz, channelConfig, audioFormat, minBufferSize, AudioTrack.MODE_STREAM);
                audioTrack.play();
                while (fis.read(buffer) != -1) {
                    audioTrack.write(buffer, 0, buffer.length);
                }
                audioTrack.stop();
                audioTrack.release();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 从网络上读取AudioTrack并播放
    public static void playOnlineAudio(String url) {
        stopPlay();
        try {
            // 获取音频文件信息
            URLConnection connection = new URL(url).openConnection();
            int sampleRateInHz = AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_MUSIC);
            int channelConfig = connection.getHeaderFieldInt("channel-config", AudioFormat.CHANNEL_OUT_STEREO);
            int audioFormat = connection.getHeaderFieldInt("audio-format", AudioFormat.ENCODING_PCM_16BIT);
            int minBufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);

            // 初始化AudioTrack并播放音频文件
            byte[] buffer = new byte[minBufferSize];
            InputStream in = connection.getInputStream();
            AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                    sampleRateInHz, channelConfig, audioFormat, minBufferSize, AudioTrack.MODE_STREAM);
            audioTrack.play();
            int length;
            while ((length = in.read(buffer)) != -1) {
                audioTrack.write(buffer, 0, length);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (audioTrack != null) {
                audioTrack.stop();
                audioTrack.release();
            }
        }
    }

    public static boolean isPlaying() {
        if (audioTrack != null) {
            int state = audioTrack.getPlayState();
            return state == AudioTrack.PLAYSTATE_PLAYING;
        }
        return false;
    }

    public static void stopPlay() {
        if (audioTrack != null) {
            audioTrack.stop();
            audioTrack.release();
        }
    }
}
